package com.dormitory.activity;

import android.app.Activity;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.dormitory.R;
import com.dormitory.adapter.FriendDormitoyListAdapter;
import com.dormitory.application.MyApplication;
import com.dormitory.bean.DormitoryBean;
import com.dormitory.controller.DormitoryController;

import java.util.List;

public class FriendDormitoryActivity extends AppCompatActivity {

    private ListView mFriendDormitoryList;
    private FriendDormitoyListAdapter mFriendDormitoyListAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friend_dormitory);

        mFriendDormitoryList = (ListView)findViewById(R.id.dormitory_list);
        mFriendDormitoyListAdapter = new FriendDormitoyListAdapter(this);
        mFriendDormitoryList.setAdapter(mFriendDormitoyListAdapter);
        mFriendDormitoryList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });

        DormitoryBean dormitoryBean = ((MyApplication)getApplication()).getDormitory();
        if(dormitoryBean != null) {
            GetFriendAsyncTask getFriendAsyncTask = new GetFriendAsyncTask();
            getFriendAsyncTask.execute(dormitoryBean.getId());
        }
    }

    private class GetFriendAsyncTask extends AsyncTask<Integer, Object, List<DormitoryBean>> {

        @Override
        protected List<DormitoryBean> doInBackground(Integer[] params) {
            DormitoryController dormitoryController = DormitoryController.getInstance();
            try {
                return dormitoryController.getFriendDormitory(params[0]);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(List<DormitoryBean> list) {
            super.onPostExecute(list);
            if(list == null) {
                Toast.makeText(FriendDormitoryActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
            }
            else {
                mFriendDormitoyListAdapter.updateDormitory(list);
            }
        }
    }
}
